/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * Copyright (c) 2023-2024 Jeremy Long. All Rights Reserved.
 */
package io.github.jeremylong.openvulnerability.client;

import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.Iterator;

/**
 * A simple wrapper around a PagedDataSource that iterates over single objects rather than a page at a time.
 *
 * @param <T> the data type
 */
public class RecordDataSource<T> implements AutoCloseable, Iterator<T> {

    private final PagedDataSource<T> source;
    private Iterator<T> current;

    public RecordDataSource(PagedDataSource<T> source) {
        this.source = source;
    }

    @Override
    public void close() throws Exception {
        source.close();
    }

    /**
     * Returns the latest updated date.
     *
     * @return the latest updated date
     */
    public ZonedDateTime getLastUpdated() {
        return source.getLastUpdated();
    }

    /**
     * Returns the last HTTP Status Code received.
     *
     * @return the last HTTP Status Code received.
     */
    public int getLastStatusCode() {
        return source.getLastStatusCode();
    }

    @Override
    public boolean hasNext() {
        return source.hasNext() || current != null && current.hasNext();
    }

    @Override
    public T next() {
        if (current == null || !current.hasNext()) {
            if (source.hasNext()) {
                Collection<T> collection = source.next();
                if (collection != null) {
                    current = collection.iterator();
                }
            }
        }
        if (current.hasNext()) {
            return current.next();
        }
        return null;
    }
}
